package game

import (
	"fmt"
	"math/rand"
	"server/GoUtil"
	"server/MergeConst"
	"server/db"
	"server/msg"
	"sort"
	"strconv"
	"strings"
	"time"

	"google.golang.org/protobuf/proto"
)

type PlayerFriendData struct {
	*PlayerData
	Data           msg.ResFriendData
	AddFriendDatas []*msg.AddFriendData
	InviteIds      []int32
	InviteGetIndex int32
	pSqlInviteSt   *db.SqlInviteFriendStruct
	sqlStruck      db.SqlFriendStruct
}

func (p *PlayerFriendData) LoadDataFromDB(dwUin interface{}) bool {

	sqlStr := "SELECT * FROM t_player_Friend_Data WHERE dwUin = ?"
	p.sqlStruck = db.SqlFriendStruct{}
	p.Data.FriendInfos = []*msg.FriendInfo{}
	p.AddFriendDatas = []*msg.AddFriendData{}
	p.InviteIds = []int32{}
	if err := db.SqlDb.Get(&p.sqlStruck, sqlStr, dwUin.(int32)); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		p.IsHaveDataDb = false
	} else {
		p.IsHaveDataDb = true
	}
	if p.sqlStruck.FriendList != "" {
		arr := strings.Split(p.sqlStruck.FriendList, "_")
		for i := 0; i < len(arr); i++ {

			id, err := strconv.ParseInt(arr[i], 10, 32)
			st := G_GameLogicPtr.MPlayerProfileManager.GetPlayerProfile(int32(id))

			DecorateCnt, ActiveTime, FaceBookId := G_GameLogicPtr.MPlayerProfileManager.GetPlayerDecorate(int32(id))

			info := msg.FriendInfo{}
			if st != nil {
				info.DwUin = st.DwUin
				info.ImageFrame = st.ImageFrame
				info.ImageIcon = st.ImageIcon
				info.NickName = st.NickName
				info.DecorateCnt = int32(DecorateCnt)
				info.ActiveTime = int32(ActiveTime)
				info.FaceBookId = FaceBookId
			} else {
				sql := &db.SqlPlayerProfileStruct{}
				sql.DwUin = int32(id)
				sql.ImageFrame = 1
				sql.ImageIcon = 1
				sql.NickName = "Player" + strconv.Itoa(int(id))
				sql.PicURL = ""
				G_GameLogicPtr.MPlayerProfileManager.UpdateNewProfile(sql)

				info.DwUin = sql.DwUin
				info.ImageFrame = sql.ImageFrame
				info.ImageIcon = sql.ImageIcon
				info.NickName = sql.NickName
				info.DecorateCnt = int32(DecorateCnt)
				info.ActiveTime = int32(ActiveTime)
				info.FaceBookId = FaceBookId
			}

			if err != nil {
				panic(err)
			}

			p.Data.FriendInfos = append(p.Data.FriendInfos, &info)
		}
	}
	p.Data.DwUin = dwUin.(int32)

	sqlStr1 := "SELECT * FROM t_player_invite_data WHERE dwUin = ?"
	p.pSqlInviteSt = &db.SqlInviteFriendStruct{}
	p.pSqlInviteSt.DwUin = p.Data.DwUin
	p.pSqlInviteSt.InviteList = ""
	if err := db.SqlDb.Get(p.pSqlInviteSt, sqlStr1, p.M_Player.M_DwUin); err != nil {

	} else {

	}
	if p.pSqlInviteSt.InviteList != "" {
		strs := strings.Split(p.pSqlInviteSt.InviteList, ";")
		for i := 0; i < len(strs); i++ {
			id, _ := strconv.Atoi(strs[i])
			p.InviteIds = append(p.InviteIds, int32(id))
		}
	}

	p.InviteGetIndex = p.pSqlInviteSt.GetIndex

	p.Reconnect(false)
	return true
}

func (p *PlayerFriendData) ReqFriendTreasureData(buf []byte) {
	req := &msg.ReqFriendTreasureData{}
	proto.Unmarshal(buf, req)
	res := &msg.ResFriendTreasureData{}
	res.Star = p.sqlStruck.TreasureStar

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResFriendTreasureData", data)
}

func (p *PlayerFriendData) ReqUpdateFriendStar(buf []byte) {
	req := &msg.ReqUpdateFriendStar{}
	proto.Unmarshal(buf, req)
	res := &msg.ResUpdateFriendStar{}
	res.Star = req.Star
	p.sqlStruck.TreasureStar = req.Star
	p.SaveDataFromDB("")

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResUpdateFriendStar", data)
}

func (p *PlayerFriendData) NotifyFriendTreasureStar() {

	res := &msg.NotifyFriendTreasureStar{}
	res.Star = 0
	p.sqlStruck.TreasureStar = 0
	p.SaveDataFromDB("")

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "NotifyFriendTreasureStar", data)
}

func (p *PlayerFriendData) RandomGetAnFriend() *msg.FriendInfo {
	var ran int
	if len(p.Data.FriendInfos) > 0 {
		ran = rand.Intn(len(p.Data.FriendInfos))
		return p.Data.FriendInfos[ran]
	}
	return nil
}

func (p *PlayerFriendData) Reconnect(b bool) {
	if b {
		p.LoadDataFromDB(p.M_Player.M_DwUin)
	}
	GoUtil.RegisterEvent(MergeConst.Notify_Daily_Renew, p.Notify_Daily_Renew, p)
}

func (p *PlayerFriendData) Notify_Daily_Renew(param []interface{}) {
	p.NotifyFriendTreasureStar()
}

func (p *PlayerFriendData) ClearData() bool {
	p.SaveDataFromDB("")
	GoUtil.RemoveEvent(MergeConst.Notify_Daily_Renew, p.Notify_Daily_Renew, p)
	return true
}

func (p *PlayerFriendData) SaveDataFromDB(Key interface{}) bool {
	var strarr []string
	for i := 0; i < len(p.Data.FriendInfos); i++ {
		str := fmt.Sprintf("%d", p.Data.FriendInfos[i].DwUin)
		strarr = append(strarr, str)
	}
	str_concat := strings.Join(strarr, "_")

	sqlStruck := db.SqlFriendStruct{}
	sqlStruck.DwUin = p.M_Player.M_DwUin
	sqlStruck.FriendList = str_concat
	sqlStruck.TreasureStar = p.sqlStruck.TreasureStar
	if p.IsHaveDataDb {
		db.FormatAllMemUpdateDb(&sqlStruck, "t_player_Friend_Data", "dwUin")
	} else {
		db.FormatAllMemInsertDb(&sqlStruck, "t_player_Friend_Data")
	}
	p.IsHaveDataDb = true
	return true
}

func (p *PlayerFriendData) ReqFriendData(player *Player) {

	// req := &msg.ReqFriendData{}
	// proto.Unmarshal(buf, req)

	for i := 0; i < len(p.Data.FriendInfos); i++ {
		id := p.Data.FriendInfos[i].DwUin
		st := G_GameLogicPtr.MPlayerProfileManager.GetPlayerProfile(id)

		DecorateCnt, ActiveTime, FaceBookId := G_GameLogicPtr.MPlayerProfileManager.GetPlayerDecorate(int32(id))
		if st != nil {
			p.Data.FriendInfos[i].ImageFrame = st.ImageFrame
			p.Data.FriendInfos[i].ImageIcon = st.ImageIcon
			p.Data.FriendInfos[i].NickName = st.NickName
			p.Data.FriendInfos[i].DecorateCnt = int32(DecorateCnt)
			p.Data.FriendInfos[i].ActiveTime = int32(ActiveTime)
			p.Data.FriendInfos[i].FaceBookId = FaceBookId
		}
	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(&p.Data)
	G_getGameLogic().PackResInfo(agent, "ResFriendData", data)
}

func (p *PlayerFriendData) IsFriend(id int32) bool {
	for i := 0; i < len(p.Data.FriendInfos); i++ {
		if p.Data.FriendInfos[i].DwUin == id {
			return true
		}

	}
	return false
}

func (p *PlayerFriendData) ReqInviteFriendData(buf []byte) {
	req := &msg.ReqInviteFriendData{}
	proto.Unmarshal(buf, req)
	res := &msg.ResInviteFriendData{}

	res.IdLists = p.InviteIds

	res.GetIndex = p.InviteGetIndex

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResInviteFriendData", data)
}

func (p *PlayerFriendData) ReqGetInviteReward(buf []byte) {
	req := &msg.ReqGetInviteReward{}
	proto.Unmarshal(buf, req)
	res := &msg.ResGetInviteReward{}

	if req.GetIndex <= p.InviteGetIndex {
		res.ResultCode = MergeConst.Protocol_AddFriend_Get_Invite_Reward
	} else {

		p.pSqlInviteSt.GetIndex = req.GetIndex
		p.InviteGetIndex = req.GetIndex
		db.FormatAllMemUpdateDb(p.pSqlInviteSt, "t_player_invite_data", "dwUin")
	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResGetInviteReward", data)
}

func (p *PlayerFriendData) ReqSelfInvited(buf []byte) {
	req := &msg.ReqSelfInvited{}
	proto.Unmarshal(buf, req)
	res := &msg.ResSelfInvited{}

	sqlStr := "SELECT * FROM t_player_invite_data WHERE dwUin = ?"
	sqlStruck := db.SqlInviteFriendStruct{}
	sqlStruck.DwUin = req.InviterId
	isHave := false
	if err := db.SqlDb.Get(&sqlStruck, sqlStr, req.InviterId); err != nil {
		isHave = false
	} else {
		isHave = true
	}
	InviteIds := []int32{}
	if sqlStruck.InviteList != "" {
		strs := strings.Split(sqlStruck.InviteList, ";")

		for i := 0; i < len(strs); i++ {
			id, _ := strconv.Atoi(strs[i])
			InviteIds = append(InviteIds, int32(id))
		}
	}

	if len(InviteIds) >= 10 {

	} else {
		isExsit := false
		for i := 0; i < len(InviteIds); i++ {
			if InviteIds[i] == p.M_Player.M_DwUin {
				isExsit = true
				break
			}
		}
		if !isExsit {
			if sqlStruck.InviteList != "" {
				jo := []string{sqlStruck.InviteList, strconv.Itoa(int(p.M_Player.M_DwUin))}
				sqlStruck.InviteList = strings.Join(jo, ";")
			} else {
				jo := []string{strconv.Itoa(int(p.M_Player.M_DwUin))}
				sqlStruck.InviteList = strings.Join(jo, ";")
			}
			if !isHave {
				db.FormatAllMemInsertDb(&sqlStruck, "t_player_invite_data")
			} else {
				db.FormatAllMemUpdateDb(&sqlStruck, "t_player_invite_data", "dwUin")
			}
			InviteIds = append(InviteIds, p.M_Player.M_DwUin)
			player, ok := G_GameLogicPtr.M_Players[req.InviterId]
			if ok {
				if player.GetGameData("PlayerFriendData") != nil {
					player.GetIFGameData("PlayerFriendData").(*PlayerFriendData).NotifyInvitedSuccess(p.M_Player.M_DwUin)
				}
			}
		} else {

		}

	}
	res.IdLists = InviteIds
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResSelfInvited", data)
}

func (p *PlayerFriendData) NotifyInvitedSuccess(inviteId int32) {
	// res.IdLists = p.InviteIds
	// p.InviteGetIndex = sqlStruck.GetIndex
	notify := &msg.NotifyInvitedSuccess{}
	p.InviteIds = append(p.InviteIds, inviteId)
	if p.pSqlInviteSt.InviteList != "" {
		jo := []string{p.pSqlInviteSt.InviteList, strconv.Itoa(int(inviteId))}
		p.pSqlInviteSt.InviteList = strings.Join(jo, ";")
	} else {
		jo := []string{strconv.Itoa(int(inviteId))}
		p.pSqlInviteSt.InviteList = strings.Join(jo, ";")
	}
	// p.pSqlInviteSt.
	// 	notify.IdLists = p.InviteIds

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyInvitedSuccess", data)
}

func (p *PlayerFriendData) ReqWillPlayerDetail(buf []byte) {

	req := &msg.ReqWillPlayerDetail{}
	proto.Unmarshal(buf, req)
	res := &msg.ResWillPlayerDetail{}
	res.PlayerInfos = []*msg.FriendInfo{}
	PlayerId, err := strconv.Atoi(req.PlayerName)

	if err == nil {
		if int32(PlayerId) == p.M_Player.M_DwUin {
			res.ResultCode = MergeConst.Protocol_AddFriend_Is_YourSelf
		} else {
			// G_getGameLogic().Mlogger.Debug("ReqWillPlayerDetail1")
			if p.IsFriend(int32(PlayerId)) {
				res.ResultCode = MergeConst.Protocol_Player_Is_Friend
			} else {
				PlayerInfos := G_GameLogicPtr.MPlayerProfileManager.GetPlayerProfileByNick(req.PlayerName)
				for i := 0; i < len(PlayerInfos); i++ {
					info := &msg.FriendInfo{}
					info.DwUin = PlayerInfos[i].DwUin
					info.ImageFrame = PlayerInfos[i].ImageFrame
					info.ImageIcon = PlayerInfos[i].ImageIcon
					info.NickName = PlayerInfos[i].NickName
					DecorateCnt, ActiveTime, FaceBookId := G_GameLogicPtr.MPlayerProfileManager.GetPlayerDecorate(PlayerInfos[i].DwUin)

					info.DecorateCnt = int32(DecorateCnt)
					info.ActiveTime = int32(ActiveTime)
					info.FaceBookId = FaceBookId
					res.PlayerInfos = append(res.PlayerInfos, info)
				}
				if len(PlayerInfos) == 0 {
					// G_getGameLogic().Mlogger.Debug("len(PlayerInfos)0:" + strconv.Itoa(len(PlayerInfos)))
					res.ResultCode = MergeConst.Protocol_Player_Not_Exsit
				}
				// st := G_GameLogicPtr.MPlayerProfileManager.GetPlayerProfile(req.PlayerId)
				// DecorateCnt := G_GameLogicPtr.MPlayerProfileManager.GetPlayerDecorate(req.PlayerId)
				// if st == nil {
				// 	isHave := G_GameLogicPtr.MPlayerProfileManager.GetIsHavePlayerById(req.PlayerId)
				// 	if !isHave {
				// 		res.ResultCode = MergeConst.Protocol_Player_Not_Exsit
				// 	} else {
				// 		res.PlayerInfo.DwUin = req.PlayerId
				// 		res.PlayerInfo.ImageFrame = 1
				// 		res.PlayerInfo.ImageIcon = 1
				// 		res.PlayerInfo.DecorateCnt = int32(DecorateCnt)
				// 		res.PlayerInfo.NickName = "Player" + strconv.Itoa(int(req.PlayerId))
				// 	}
				// } else {
				// 	res.PlayerInfo.DwUin = st.DwUin
				// 	res.PlayerInfo.ImageFrame = st.ImageFrame
				// 	res.PlayerInfo.ImageIcon = st.ImageIcon
				// 	res.PlayerInfo.NickName = st.NickName
				// 	res.PlayerInfo.DecorateCnt = int32(DecorateCnt)
				// }
			}
		}
	} else {
		PlayerInfos := G_GameLogicPtr.MPlayerProfileManager.GetPlayerProfileByNick(req.PlayerName)
		// G_getGameLogic().Mlogger.Debug("ReqWillPlayerDetail2")
		maxIdx := len(PlayerInfos) - 1
		for i := maxIdx; i >= 0; i-- {
			if p.M_Player.M_DwUin == PlayerInfos[i].DwUin {
				PlayerInfos = append(PlayerInfos[:i], PlayerInfos[i+1:]...)
			}
		}

		for i := 0; i < len(PlayerInfos); i++ {
			info := &msg.FriendInfo{}
			info.DwUin = PlayerInfos[i].DwUin
			info.ImageFrame = PlayerInfos[i].ImageFrame
			info.ImageIcon = PlayerInfos[i].ImageIcon
			info.NickName = PlayerInfos[i].NickName
			DecorateCnt, ActiveTime, FaceBookId := G_GameLogicPtr.MPlayerProfileManager.GetPlayerDecorate(PlayerInfos[i].DwUin)
			info.DecorateCnt = int32(DecorateCnt)
			info.ActiveTime = int32(ActiveTime)
			info.FaceBookId = FaceBookId
			res.PlayerInfos = append(res.PlayerInfos, info)
		}
		if len(PlayerInfos) == 0 {
			res.ResultCode = MergeConst.Protocol_Player_Not_Exsit
			// G_getGameLogic().Mlogger.Debug("len(PlayerInfos)1:" + strconv.Itoa(len(PlayerInfos)))
		}
	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResWillPlayerDetail", data)
}

func (p *PlayerFriendData) GetIsHaveAddFriendInfo(sender int32, receive int32) (bool, *db.SqlAddFriendStruct) {
	sqlStr := "SELECT * FROM t_player_Req_add_Friend WHERE SenderId = ? AND ReceiverId = ?"
	sqlStruck := db.SqlAddFriendStruct{}

	if err := db.SqlDb.Get(&sqlStruck, sqlStr, sender, receive); err != nil {
		return false, nil
	} else {
		return true, &sqlStruck
	}
	// return false
}

func (p *PlayerFriendData) ReqAllAddFriendInfo(buf []byte) {

	req := &msg.ReqAllAddFriendInfo{}
	proto.Unmarshal(buf, req)
	res := &msg.ResAllAddFriendInfo{}

	sqlStr := "SELECT * FROM t_player_Req_add_Friend WHERE ReceiverId = ?"
	sqlStruck := []db.SqlAddFriendStruct{}
	res.FriendInfos = []*msg.AddFriendData{}
	if err := db.SqlDb.Select(&sqlStruck, sqlStr, p.M_Player.M_DwUin); err != nil {

	} else {

	}
	for i := 0; i < len(sqlStruck); i++ {
		temp := &msg.AddFriendData{}
		temp.AutoId = sqlStruck[i].Auto_id
		temp.Finfo = &msg.FriendInfo{}
		Profile := G_GameLogicPtr.MPlayerProfileManager.GetPlayerProfile(sqlStruck[i].SenderId)

		DecorateCnt, ActiveTime, FaceBookId := G_GameLogicPtr.MPlayerProfileManager.GetPlayerDecorate(sqlStruck[i].SenderId)
		if Profile != nil {
			temp.Finfo.DwUin = Profile.DwUin
			temp.Finfo.ImageFrame = Profile.ImageFrame
			temp.Finfo.ImageIcon = Profile.ImageIcon
			temp.Finfo.NickName = Profile.NickName
			temp.Finfo.DecorateCnt = int32(DecorateCnt)
			temp.Finfo.ActiveTime = int32(ActiveTime)
			temp.Finfo.FaceBookId = FaceBookId
		} else {
			temp.Finfo.DwUin = sqlStruck[i].SenderId
			temp.Finfo.ImageFrame = 1
			temp.Finfo.ImageIcon = 1
			temp.Finfo.NickName = "Player" + strconv.Itoa(int(sqlStruck[i].SenderId))
			temp.Finfo.DecorateCnt = int32(DecorateCnt)
			temp.Finfo.ActiveTime = int32(ActiveTime)
			temp.Finfo.FaceBookId = FaceBookId
			sql := &db.SqlPlayerProfileStruct{}
			sql.DwUin = sqlStruck[i].SenderId
			sql.ImageFrame = 1
			sql.ImageIcon = 1
			sql.NickName = "Player" + strconv.Itoa(int(sqlStruck[i].SenderId))
			sql.PicURL = ""
			G_GameLogicPtr.MPlayerProfileManager.UpdateNewProfile(sql)
		}
		res.FriendInfos = append(res.FriendInfos, temp)
		p.AddFriendDatas = res.FriendInfos
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResAllAddFriendInfo", data)
}

func (p *PlayerFriendData) ReqRecommendFriendList(buf []byte) {
	req := &msg.ReqRecommendFriendList{}
	proto.Unmarshal(buf, req)
	res := &msg.ResRecommendFriendList{}

	res.PlayerInfos = []*msg.FriendInfo{}

	req.ExcludeList = append(req.ExcludeList, p.M_Player.M_DwUin)
	for i := 0; i < len(p.Data.FriendInfos); i++ {
		req.ExcludeList = append(req.ExcludeList, p.Data.FriendInfos[i].DwUin)
	}

	RecommondPlayers := G_GameLogicPtr.MPlayerProfileManager.RandomGetPlayers(int(req.RecommendCnt), p.M_Player.M_DwUin, req.ExcludeList)

	for i := 0; i < len(RecommondPlayers); i++ {
		DecorateCnt, ActiveTime, FaceBookId := G_GameLogicPtr.MPlayerProfileManager.GetPlayerDecorate(RecommondPlayers[i].DwUin)
		Finfo := &msg.FriendInfo{}
		Finfo.DwUin = RecommondPlayers[i].DwUin
		Finfo.ImageFrame = RecommondPlayers[i].ImageFrame
		Finfo.ImageIcon = RecommondPlayers[i].ImageIcon
		Finfo.NickName = RecommondPlayers[i].NickName
		Finfo.DecorateCnt = int32(DecorateCnt)
		Finfo.ActiveTime = int32(ActiveTime)
		Finfo.FaceBookId = FaceBookId
		res.PlayerInfos = append(res.PlayerInfos, Finfo)
	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResRecommendFriendList", data)
}

func (p *PlayerFriendData) ReqAddFriendData(buf []byte) {

	req := &msg.ReqAddFriendData{}
	proto.Unmarshal(buf, req)
	res := &msg.ResAddFriendData{}

	sqlStruck := db.SqlAddFriendStruct{}

	isHave, _ := p.GetIsHaveAddFriendInfo(req.SenderId, req.ReceiverId)
	isHave1, _ := p.GetIsHaveAddFriendInfo(req.ReceiverId, req.SenderId)
	if isHave {
		res.ResultCode = MergeConst.Protocol_AddFriend_Is_Send
	} else {
		res.ResultCode = 0
		if isHave1 {
			res.ResultCode = MergeConst.Protocol_AddFriend_Is_Target_Send
			agent := p.GetPlayer().GetAgentByPlayer()
			data, _ := proto.Marshal(res)
			G_getGameLogic().PackResInfo(agent, "ResAddFriendData", data)
			return
		}

		if p.IsFriend(req.ReceiverId) {
			res.ResultCode = MergeConst.Protocol_Player_Is_Friend
			agent := p.GetPlayer().GetAgentByPlayer()
			data, _ := proto.Marshal(res)
			G_getGameLogic().PackResInfo(agent, "ResAddFriendData", data)
			return
		}

		sqlStruck.SenderId = req.SenderId
		sqlStruck.ReceiverId = req.ReceiverId
		insertId, _ := db.FormatAllMemInsertDb(&sqlStruck, "t_player_Req_add_Friend")
		////////通知被添加好友请求的玩家
		notify := &msg.NotifyAddFriendReq{}
		notify.ReqInfo = &msg.AddFriendData{}
		notify.ReqInfo.Finfo = &msg.FriendInfo{}
		notify.ReqInfo.AutoId = int32(insertId)
		notify.ReqInfo.Finfo.DwUin = p.M_Player.M_DwUin
		Profile := G_GameLogicPtr.MPlayerProfileManager.GetPlayerProfile(p.M_Player.M_DwUin)

		DecorateCnt, ActiveTime, FaceBookId := G_GameLogicPtr.MPlayerProfileManager.GetPlayerDecorate(p.M_Player.M_DwUin)

		if Profile != nil {
			notify.ReqInfo.Finfo.ImageFrame = Profile.ImageFrame
			notify.ReqInfo.Finfo.ImageIcon = Profile.ImageIcon
			notify.ReqInfo.Finfo.NickName = Profile.NickName
			notify.ReqInfo.Finfo.DecorateCnt = int32(DecorateCnt)
			notify.ReqInfo.Finfo.ActiveTime = int32(ActiveTime)
			notify.ReqInfo.Finfo.FaceBookId = FaceBookId
		} else {
			notify.ReqInfo.Finfo.ImageFrame = 1
			notify.ReqInfo.Finfo.ImageIcon = 1
			notify.ReqInfo.Finfo.NickName = "Player" + strconv.Itoa(int(p.M_Player.M_DwUin))
			notify.ReqInfo.Finfo.DecorateCnt = int32(DecorateCnt)
			notify.ReqInfo.Finfo.ActiveTime = int32(ActiveTime)
			notify.ReqInfo.Finfo.FaceBookId = FaceBookId
			sql := &db.SqlPlayerProfileStruct{}
			sql.DwUin = p.M_Player.M_DwUin
			sql.ImageFrame = 1
			sql.ImageIcon = 1
			sql.NickName = "Player" + strconv.Itoa(int(p.M_Player.M_DwUin))
			sql.PicURL = ""
			G_GameLogicPtr.MPlayerProfileManager.UpdateNewProfile(sql)
		}
		data, _ := proto.Marshal(notify)
		G_GameLogicPtr.SendMassage(req.ReceiverId, "NotifyAddFriendReq", data)

		EventAuid, sqlst, friendInfo := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).NewFriendEventToDb(1, req.ReceiverId, req.SenderId, []interface{}{int32(insertId)})
		player, ok := G_GameLogicPtr.M_Players[req.ReceiverId]
		if ok {
			if player.GetGameData("PlayerFriendEventData") != nil {
				player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).NotifyNewFriendEvent(EventAuid, sqlst, friendInfo)
			}
		}
	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResAddFriendData", data)
}

func (p *PlayerFriendData) GetAddFriendData(auto int32) *msg.AddFriendData {
	for i := 0; i < len(p.AddFriendDatas); i++ {
		if p.AddFriendDatas[i].AutoId == auto {
			return p.AddFriendDatas[i]
		}
	}
	return nil
}

/////

func (p *PlayerFriendData) ReqAutoFBAddFriend(buf []byte) {

	req := &msg.ReqAutoFBAddFriend{}
	proto.Unmarshal(buf, req)
	res := &msg.ResAutoFBAddFriend{}

	for m := 0; m < len(req.FbIds); m++ {
		findSql := "SELECT * FROM t_player_baseinfo WHERE FaceBookId = ?"
		sqlStruckBInfo := db.ResPlayerBaseInfo{}
		var PlayerId int32 = 0

		if err2 := db.SqlDb.Get(&sqlStruckBInfo, findSql, req.FbIds[m]); err2 != nil {

			continue
		} else {
			PlayerId = sqlStruckBInfo.DwUin
		}
		if PlayerId == p.M_Player.M_DwUin {
			continue
		}
		if p.IsFriend(PlayerId) {
			continue
		}
		sqlStrs := []string{}

		sqlStr := "SELECT * FROM t_player_Friend_Data WHERE dwUin = ?"
		sqlStruck := db.SqlFriendStruct{}
		sqlStruck.FriendList = ""
		sqlStruck.DwUin = p.M_Player.M_DwUin
		isHave := false

		if err := db.SqlDb.Get(&sqlStruck, sqlStr, p.M_Player.M_DwUin); err != nil {
			isHave = false
		} else {
			isHave = true
		}
		atrarr := []string{}
		if sqlStruck.FriendList != "" {
			atrarr = append(atrarr, sqlStruck.FriendList)
		}
		atrarr = append(atrarr, strconv.Itoa(int(PlayerId)))
		sqlStruck.FriendList = strings.Join(atrarr, "_")
		params := [][]any{}
		if isHave {
			sqlStrs = append(sqlStrs, "UPDATE t_player_Friend_Data SET FriendList = ? WHERE dwUin = ?")

			t1 := []any{}
			t1 = append(t1, sqlStruck.FriendList)
			t1 = append(t1, sqlStruck.DwUin)
			params = append(params, t1)
		} else {
			sqlStrs = append(sqlStrs, "INSERT INTO t_player_Friend_Data(dwUin, FriendList) VALUES(?, ?)")
			p.IsHaveDataDb = true
			t1 := []any{}
			t1 = append(t1, p.M_Player.M_DwUin)
			t1 = append(t1, sqlStruck.FriendList)
			params = append(params, t1)
		}
		//////////////
		sqlStruck1 := db.SqlFriendStruct{}
		sqlStruck1.FriendList = ""
		isHave1 := false
		if err := db.SqlDb.Get(&sqlStruck1, sqlStr, PlayerId); err != nil {
			isHave1 = false
		} else {
			isHave1 = true
		}
		atrarr1 := []string{}

		if sqlStruck1.FriendList != "" {
			atrarr1 = append(atrarr1, sqlStruck1.FriendList)
		}
		atrarr1 = append(atrarr1, strconv.Itoa(int(p.M_Player.M_DwUin)))
		sqlStruck1.FriendList = strings.Join(atrarr1, "_")

		if isHave1 {
			sqlStrs = append(sqlStrs, "UPDATE t_player_Friend_Data SET FriendList = ? WHERE dwUin = ?")

			t1 := []any{}
			t1 = append(t1, sqlStruck1.FriendList)
			t1 = append(t1, sqlStruck1.DwUin)
			params = append(params, t1)
		} else {
			sqlStrs = append(sqlStrs, "INSERT INTO t_player_Friend_Data(dwUin, FriendList) VALUES(?, ?)")

			t1 := []any{}
			t1 = append(t1, PlayerId)
			t1 = append(t1, sqlStruck1.FriendList)
			params = append(params, t1)
		}
		err := db.SeriesTransaction(sqlStrs, params)
		if err == nil {
			finfo := &msg.FriendInfo{}
			Profile := G_GameLogicPtr.MPlayerProfileManager.GetPlayerProfile(PlayerId)
			DecorateCnt, ActiveTime, FaceBookId := G_GameLogicPtr.MPlayerProfileManager.GetPlayerDecorate(PlayerId)
			if Profile != nil {

				finfo.DwUin = Profile.DwUin
				finfo.ImageFrame = Profile.ImageFrame
				finfo.ImageIcon = Profile.ImageIcon
				finfo.NickName = Profile.NickName
				finfo.DecorateCnt = int32(DecorateCnt)
				finfo.ActiveTime = int32(ActiveTime)
				finfo.FaceBookId = FaceBookId
			} else {

				finfo.DwUin = PlayerId
				finfo.ImageFrame = 1
				finfo.ImageIcon = 1
				finfo.NickName = "Player" + strconv.Itoa(int(PlayerId))
				finfo.DecorateCnt = int32(DecorateCnt)
				finfo.ActiveTime = int32(ActiveTime)
				finfo.FaceBookId = FaceBookId

				sql := &db.SqlPlayerProfileStruct{}
				sql.DwUin = PlayerId
				sql.ImageFrame = 1
				sql.ImageIcon = 1
				sql.NickName = "Player" + strconv.Itoa(int(PlayerId))
				sql.PicURL = ""
				G_GameLogicPtr.MPlayerProfileManager.UpdateNewProfile(sql)
			}
			p.Data.FriendInfos = append(p.Data.FriendInfos, finfo)

			player, ok := G_GameLogicPtr.M_Players[PlayerId]
			if ok {
				if player.GetGameData("PlayerFriendData") != nil {
					player.GetIFGameData("PlayerFriendData").(*PlayerFriendData).NotifySuccessFBAddFriend(p.M_Player.M_DwUin)
				}
			}

		}
	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResAutoFBAddFriend", data)
}

func (p *PlayerFriendData) ReqAutoAddInviteFriend(buf []byte) {

	req := &msg.ReqAutoAddInviteFriend{}
	proto.Unmarshal(buf, req)
	res := &msg.ResAutoAddInviteFriend{}

	for m := 0; m < len(req.Ids); m++ {
		findSql := "SELECT * FROM t_player_baseinfo WHERE dwUin = ?"
		sqlStruckBInfo := db.ResPlayerBaseInfo{}
		tempId, _ := strconv.Atoi(req.Ids[m])
		var PlayerId int32 = int32(tempId)

		if err2 := db.SqlDb.Get(&sqlStruckBInfo, findSql, req.Ids[m]); err2 != nil {

		} else {
			PlayerId = sqlStruckBInfo.DwUin
		}
		if PlayerId == p.M_Player.M_DwUin {
			continue
		}
		if p.IsFriend(PlayerId) {
			continue
		}
		sqlStrs := []string{}

		sqlStr := "SELECT * FROM t_player_Friend_Data WHERE dwUin = ?"
		sqlStruck := db.SqlFriendStruct{}
		sqlStruck.FriendList = ""
		sqlStruck.DwUin = p.M_Player.M_DwUin
		isHave := false

		if err := db.SqlDb.Get(&sqlStruck, sqlStr, p.M_Player.M_DwUin); err != nil {
			isHave = false
		} else {
			isHave = true
		}
		atrarr := []string{}
		if sqlStruck.FriendList != "" {
			atrarr = append(atrarr, sqlStruck.FriendList)
		}
		atrarr = append(atrarr, strconv.Itoa(int(PlayerId)))
		sqlStruck.FriendList = strings.Join(atrarr, "_")
		params := [][]any{}
		if isHave {
			sqlStrs = append(sqlStrs, "UPDATE t_player_Friend_Data SET FriendList = ? WHERE dwUin = ?")

			t1 := []any{}
			t1 = append(t1, sqlStruck.FriendList)
			t1 = append(t1, sqlStruck.DwUin)
			params = append(params, t1)
		} else {
			sqlStrs = append(sqlStrs, "INSERT INTO t_player_Friend_Data(dwUin, FriendList) VALUES(?, ?)")
			p.IsHaveDataDb = true
			t1 := []any{}
			t1 = append(t1, p.M_Player.M_DwUin)
			t1 = append(t1, sqlStruck.FriendList)
			params = append(params, t1)
		}
		//////////////
		sqlStruck1 := db.SqlFriendStruct{}
		sqlStruck1.FriendList = ""
		isHave1 := false
		if err := db.SqlDb.Get(&sqlStruck1, sqlStr, PlayerId); err != nil {
			isHave1 = false
		} else {
			isHave1 = true
		}
		atrarr1 := []string{}

		if sqlStruck1.FriendList != "" {
			atrarr1 = append(atrarr1, sqlStruck1.FriendList)
		}
		atrarr1 = append(atrarr1, strconv.Itoa(int(p.M_Player.M_DwUin)))
		sqlStruck1.FriendList = strings.Join(atrarr1, "_")

		if isHave1 {
			sqlStrs = append(sqlStrs, "UPDATE t_player_Friend_Data SET FriendList = ? WHERE dwUin = ?")

			t1 := []any{}
			t1 = append(t1, sqlStruck1.FriendList)
			t1 = append(t1, sqlStruck1.DwUin)
			params = append(params, t1)
		} else {
			sqlStrs = append(sqlStrs, "INSERT INTO t_player_Friend_Data(dwUin, FriendList) VALUES(?, ?)")

			t1 := []any{}
			t1 = append(t1, PlayerId)
			t1 = append(t1, sqlStruck1.FriendList)
			params = append(params, t1)
		}
		err := db.SeriesTransaction(sqlStrs, params)
		if err == nil {
			finfo := &msg.FriendInfo{}
			Profile := G_GameLogicPtr.MPlayerProfileManager.GetPlayerProfile(PlayerId)
			DecorateCnt, ActiveTime, FaceBookId := G_GameLogicPtr.MPlayerProfileManager.GetPlayerDecorate(PlayerId)
			if Profile != nil {

				finfo.DwUin = Profile.DwUin
				finfo.ImageFrame = Profile.ImageFrame
				finfo.ImageIcon = Profile.ImageIcon
				finfo.NickName = Profile.NickName
				finfo.DecorateCnt = int32(DecorateCnt)
				finfo.ActiveTime = int32(ActiveTime)
				finfo.FaceBookId = FaceBookId
			} else {

				finfo.DwUin = PlayerId
				finfo.ImageFrame = 1
				finfo.ImageIcon = 1
				finfo.NickName = "Player" + strconv.Itoa(int(PlayerId))
				finfo.DecorateCnt = int32(DecorateCnt)
				finfo.ActiveTime = int32(ActiveTime)
				finfo.FaceBookId = FaceBookId

				sql := &db.SqlPlayerProfileStruct{}
				sql.DwUin = PlayerId
				sql.ImageFrame = 1
				sql.ImageIcon = 1
				sql.NickName = "Player" + strconv.Itoa(int(PlayerId))
				sql.PicURL = ""
				G_GameLogicPtr.MPlayerProfileManager.UpdateNewProfile(sql)
			}
			p.Data.FriendInfos = append(p.Data.FriendInfos, finfo)

			player, ok := G_GameLogicPtr.M_Players[PlayerId]
			if ok {
				if player.GetGameData("PlayerFriendData") != nil {
					player.GetIFGameData("PlayerFriendData").(*PlayerFriendData).NotifySuccessInviteAddFriend(p.M_Player.M_DwUin)
				}
			}

		}
	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResAutoAddInviteFriend", data)
}

///////////////

func (p *PlayerFriendData) ReqAgreeFriendReq(buf []byte) {

	req := &msg.ReqAgreeFriendReq{}
	proto.Unmarshal(buf, req)
	res := &msg.ResAgreeFriendReq{}
	res.Data = &msg.FriendInfo{}
	res.AutoId = req.AutoId
	addfriendData := p.GetAddFriendData(req.AutoId)
	if addfriendData != nil {
		if p.IsFriend(addfriendData.Finfo.DwUin) {
			res.ResultCode = MergeConst.Protocol_Player_Is_Friend
			agent := p.GetPlayer().GetAgentByPlayer()
			data, _ := proto.Marshal(res)
			G_getGameLogic().PackResInfo(agent, "ResAgreeFriendReq", data)

			EventAI := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteEventDbData(p.M_Player.M_DwUin, 1, req.AutoId)
			p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteLocalDataByAutoId(EventAI)

			sqlStr := "DELETE FROM t_player_Req_add_Friend WHERE auto_id = ?"
			db.SqlDb.Exec(sqlStr, req.AutoId)
			return
		}
		res.Data = addfriendData.Finfo

		sqlStrs := []string{}
		sqlStrs = append(sqlStrs, "DELETE FROM t_player_Req_add_Friend WHERE auto_id = ?")
		params := [][]any{}
		t1 := []any{}
		t1 = append(t1, req.AutoId)
		params = append(params, t1)

		sqlStr := "SELECT * FROM t_player_Friend_Data WHERE dwUin = ?"
		sqlStruck := db.SqlFriendStruct{}
		sqlStruck.FriendList = ""
		sqlStruck.DwUin = p.M_Player.M_DwUin
		isHave := false
		if err := db.SqlDb.Get(&sqlStruck, sqlStr, p.M_Player.M_DwUin); err != nil {
			isHave = false
		} else {
			isHave = true
		}
		atrarr := []string{}
		if sqlStruck.FriendList != "" {
			atrarr = append(atrarr, sqlStruck.FriendList)
		}
		atrarr = append(atrarr, strconv.Itoa(int(addfriendData.Finfo.DwUin)))
		sqlStruck.FriendList = strings.Join(atrarr, "_")

		if isHave {
			sqlStrs = append(sqlStrs, "UPDATE t_player_Friend_Data SET FriendList = ? WHERE dwUin = ?")

			t1 := []any{}
			t1 = append(t1, sqlStruck.FriendList)
			t1 = append(t1, sqlStruck.DwUin)
			params = append(params, t1)
		} else {
			sqlStrs = append(sqlStrs, "INSERT INTO t_player_Friend_Data(dwUin, FriendList) VALUES(?, ?)")
			p.IsHaveDataDb = true
			t1 := []any{}
			t1 = append(t1, p.M_Player.M_DwUin)
			t1 = append(t1, sqlStruck.FriendList)
			params = append(params, t1)
		}
		//////////////
		sqlStruck1 := db.SqlFriendStruct{}
		sqlStruck1.FriendList = ""
		isHave1 := false
		if err := db.SqlDb.Get(&sqlStruck1, sqlStr, addfriendData.Finfo.DwUin); err != nil {
			isHave1 = false
		} else {
			isHave1 = true
		}
		atrarr1 := []string{}

		if sqlStruck1.FriendList != "" {
			atrarr1 = append(atrarr1, sqlStruck1.FriendList)
		}
		atrarr1 = append(atrarr1, strconv.Itoa(int(p.M_Player.M_DwUin)))
		sqlStruck1.FriendList = strings.Join(atrarr1, "_")

		if isHave1 {
			sqlStrs = append(sqlStrs, "UPDATE t_player_Friend_Data SET FriendList = ? WHERE dwUin = ?")

			t1 := []any{}
			t1 = append(t1, sqlStruck1.FriendList)
			t1 = append(t1, sqlStruck1.DwUin)
			params = append(params, t1)
		} else {
			sqlStrs = append(sqlStrs, "INSERT INTO t_player_Friend_Data(dwUin, FriendList) VALUES(?, ?)")

			t1 := []any{}
			t1 = append(t1, addfriendData.Finfo.DwUin)
			t1 = append(t1, sqlStruck1.FriendList)
			params = append(params, t1)
		}
		err := db.SeriesTransaction(sqlStrs, params)
		if err == nil {
			finfo := &msg.FriendInfo{}
			Profile := G_GameLogicPtr.MPlayerProfileManager.GetPlayerProfile(addfriendData.Finfo.DwUin)
			DecorateCnt, ActiveTime, FaceBookId := G_GameLogicPtr.MPlayerProfileManager.GetPlayerDecorate(addfriendData.Finfo.DwUin)
			if Profile != nil {

				finfo.DwUin = Profile.DwUin
				finfo.ImageFrame = Profile.ImageFrame
				finfo.ImageIcon = Profile.ImageIcon
				finfo.NickName = Profile.NickName
				finfo.DecorateCnt = int32(DecorateCnt)
				finfo.ActiveTime = int32(ActiveTime)
				finfo.FaceBookId = FaceBookId
			} else {

				finfo.DwUin = addfriendData.Finfo.DwUin
				finfo.ImageFrame = 1
				finfo.ImageIcon = 1
				finfo.NickName = "Player" + strconv.Itoa(int(addfriendData.Finfo.DwUin))
				finfo.DecorateCnt = int32(DecorateCnt)
				finfo.ActiveTime = int32(ActiveTime)
				finfo.FaceBookId = FaceBookId

				sql := &db.SqlPlayerProfileStruct{}
				sql.DwUin = addfriendData.Finfo.DwUin
				sql.ImageFrame = 1
				sql.ImageIcon = 1
				sql.NickName = "Player" + strconv.Itoa(int(addfriendData.Finfo.DwUin))
				sql.PicURL = ""
				G_GameLogicPtr.MPlayerProfileManager.UpdateNewProfile(sql)
			}
			p.Data.FriendInfos = append(p.Data.FriendInfos, finfo)

			EventAuid, sqlst, friendInfo := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).NewFriendEventToDb(2, p.M_Player.M_DwUin, addfriendData.Finfo.DwUin, []interface{}{req.AutoId})
			p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).NotifyNewFriendEvent(EventAuid, sqlst, friendInfo)
			EventAI := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteEventDbData(p.M_Player.M_DwUin, 1, req.AutoId)
			p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteLocalDataByAutoId(EventAI)

			EventAuid1, sqlst1, friendInfo1 := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).NewFriendEventToDb(2, addfriendData.Finfo.DwUin, p.M_Player.M_DwUin, []interface{}{int32(req.AutoId)})
			player, ok := G_GameLogicPtr.M_Players[addfriendData.Finfo.DwUin]
			if ok {
				if player.GetGameData("PlayerFriendData") != nil {
					player.GetIFGameData("PlayerFriendData").(*PlayerFriendData).NotifySuccessAddFriend(req.AutoId, p.M_Player.M_DwUin)
				}
				if player.GetGameData("PlayerFriendEventData") != nil {

					player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).NotifyNewFriendEvent(EventAuid1, sqlst1, friendInfo1)
				}
			}
			for i := 0; i < len(p.AddFriendDatas); i++ {
				if p.AddFriendDatas[i].AutoId == req.AutoId {
					p.AddFriendDatas = append(p.AddFriendDatas[:i], p.AddFriendDatas[i+1:]...)
					break
				}
			}

		}

	} else {
		res.ResultCode = MergeConst.Protocol_AddFriend_Is_NoExsit
	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResAgreeFriendReq", data)
}

func (p *PlayerFriendData) NotifySuccessInviteAddFriend(FriendId int32) {
	notify := &msg.NotifySuccessInviteAddFriend{}

	notify.Data = &msg.FriendInfo{}

	Profile := G_GameLogicPtr.MPlayerProfileManager.GetPlayerProfile(FriendId)
	DecorateCnt, ActiveTime, FaceBookId := G_GameLogicPtr.MPlayerProfileManager.GetPlayerDecorate(FriendId)
	if Profile != nil {
		notify.Data.ImageFrame = Profile.ImageFrame
		notify.Data.ImageIcon = Profile.ImageIcon
		notify.Data.NickName = Profile.NickName
		notify.Data.DwUin = Profile.DwUin
		notify.Data.DecorateCnt = int32(DecorateCnt)
		notify.Data.ActiveTime = int32(ActiveTime)
		notify.Data.FaceBookId = FaceBookId
	} else {
		notify.Data.ImageFrame = 1
		notify.Data.ImageIcon = 1
		notify.Data.NickName = "Player" + strconv.Itoa(int(FriendId))
		notify.Data.DwUin = FriendId
		notify.Data.DecorateCnt = int32(DecorateCnt)
		notify.Data.ActiveTime = int32(ActiveTime)
		notify.Data.FaceBookId = FaceBookId
		sql := &db.SqlPlayerProfileStruct{}
		sql.DwUin = FriendId
		sql.ImageFrame = 1
		sql.ImageIcon = 1
		sql.NickName = "Player" + strconv.Itoa(int(FriendId))
		sql.PicURL = ""
		G_GameLogicPtr.MPlayerProfileManager.UpdateNewProfile(sql)
	}
	p.Data.FriendInfos = append(p.Data.FriendInfos, notify.Data)
	p.IsHaveDataDb = true
	agent := p.M_Player.GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifySuccessInviteAddFriend", data)

}

func (p *PlayerFriendData) NotifySuccessFBAddFriend(FriendId int32) {
	notify := &msg.NotifySuccessFBAddFriend{}

	notify.Data = &msg.FriendInfo{}

	Profile := G_GameLogicPtr.MPlayerProfileManager.GetPlayerProfile(FriendId)
	DecorateCnt, ActiveTime, FaceBookId := G_GameLogicPtr.MPlayerProfileManager.GetPlayerDecorate(FriendId)
	if Profile != nil {
		notify.Data.ImageFrame = Profile.ImageFrame
		notify.Data.ImageIcon = Profile.ImageIcon
		notify.Data.NickName = Profile.NickName
		notify.Data.DwUin = Profile.DwUin
		notify.Data.DecorateCnt = int32(DecorateCnt)
		notify.Data.ActiveTime = int32(ActiveTime)
		notify.Data.FaceBookId = FaceBookId
	} else {
		notify.Data.ImageFrame = 1
		notify.Data.ImageIcon = 1
		notify.Data.NickName = "Player" + strconv.Itoa(int(FriendId))
		notify.Data.DwUin = FriendId
		notify.Data.DecorateCnt = int32(DecorateCnt)
		notify.Data.ActiveTime = int32(ActiveTime)
		notify.Data.FaceBookId = FaceBookId
		sql := &db.SqlPlayerProfileStruct{}
		sql.DwUin = FriendId
		sql.ImageFrame = 1
		sql.ImageIcon = 1
		sql.NickName = "Player" + strconv.Itoa(int(FriendId))
		sql.PicURL = ""
		G_GameLogicPtr.MPlayerProfileManager.UpdateNewProfile(sql)
	}
	p.Data.FriendInfos = append(p.Data.FriendInfos, notify.Data)
	p.IsHaveDataDb = true
	agent := p.M_Player.GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifySuccessFBAddFriend", data)

}

func (p *PlayerFriendData) NotifySuccessAddFriend(AutoId int32, FriendId int32) {
	notify := &msg.NotifyAgreeAddFriend{}
	notify.AutoId = AutoId
	notify.Data = &msg.FriendInfo{}

	Profile := G_GameLogicPtr.MPlayerProfileManager.GetPlayerProfile(FriendId)
	DecorateCnt, ActiveTime, FaceBookId := G_GameLogicPtr.MPlayerProfileManager.GetPlayerDecorate(FriendId)
	if Profile != nil {
		notify.Data.ImageFrame = Profile.ImageFrame
		notify.Data.ImageIcon = Profile.ImageIcon
		notify.Data.NickName = Profile.NickName
		notify.Data.DwUin = Profile.DwUin
		notify.Data.DecorateCnt = int32(DecorateCnt)
		notify.Data.ActiveTime = int32(ActiveTime)
		notify.Data.FaceBookId = FaceBookId
	} else {
		notify.Data.ImageFrame = 1
		notify.Data.ImageIcon = 1
		notify.Data.NickName = "Player" + strconv.Itoa(int(FriendId))
		notify.Data.DwUin = FriendId
		notify.Data.DecorateCnt = int32(DecorateCnt)
		notify.Data.ActiveTime = int32(ActiveTime)
		notify.Data.FaceBookId = FaceBookId
		sql := &db.SqlPlayerProfileStruct{}
		sql.DwUin = FriendId
		sql.ImageFrame = 1
		sql.ImageIcon = 1
		sql.NickName = "Player" + strconv.Itoa(int(FriendId))
		sql.PicURL = ""
		G_GameLogicPtr.MPlayerProfileManager.UpdateNewProfile(sql)
	}
	p.Data.FriendInfos = append(p.Data.FriendInfos, notify.Data)
	p.IsHaveDataDb = true
	agent := p.M_Player.GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyAgreeAddFriend", data)

}

func (p *PlayerFriendData) ReqRefuseFriendReq(buf []byte) {
	req := &msg.ReqRefuseFriendReq{}
	proto.Unmarshal(buf, req)
	res := &msg.ResRefuseFriendReq{}

	sqlStr := "DELETE FROM t_player_Req_add_Friend WHERE auto_id = ?"
	result, err := db.SqlDb.Exec(sqlStr, req.AutoId)

	if err != nil {
		fmt.Printf("exec failed, err:%v\n", err)
	}
	affectedRows, err := result.RowsAffected()

	if err != nil {
		fmt.Printf("get affected failed, err:%v\n", err)

	} else {
		if affectedRows > 0 {
			res.ResultCode = 0
			for i := 0; i < len(p.AddFriendDatas); i++ {
				if p.AddFriendDatas[i].AutoId == req.AutoId {
					p.AddFriendDatas = append(p.AddFriendDatas[:i], p.AddFriendDatas[i+1:]...)
					break
				}
			}
			EventAI := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteEventDbData(p.M_Player.M_DwUin, 1, req.AutoId)
			p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteLocalDataByAutoId(EventAI)
		} else {
			res.ResultCode = MergeConst.Protocol_AddFriend_Is_NoExsit
		}
	}
	fmt.Printf("delete data success, affected rows:%d\n", affectedRows)
	res.AutoId = req.AutoId

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResRefuseFriendReq", data)
}

func (p *PlayerFriendData) ReqDeleteFriend(buf []byte) {
	req := &msg.ReqDeleteFriend{}
	proto.Unmarshal(buf, req)
	res := &msg.ResDeleteFriend{}
	res.PlayerId = req.PlayerId
	var strarr []string
	ishave := false
	for i := 0; i < len(p.Data.FriendInfos); i++ {
		if p.Data.FriendInfos[i].DwUin == req.PlayerId {
			p.Data.FriendInfos = append(p.Data.FriendInfos[:i], p.Data.FriendInfos[i+1:]...)
			ishave = true
			break
		}
	}
	if ishave {
		for i := 0; i < len(p.Data.FriendInfos); i++ {
			str := fmt.Sprintf("%d", p.Data.FriendInfos[i].DwUin)
			strarr = append(strarr, str)
		}
		str_concat := strings.Join(strarr, "_")

		sqlStrs := []string{}
		sqlStrs = append(sqlStrs, "UPDATE t_player_Friend_Data SET FriendList = ? WHERE dwUin = ?")
		params := [][]any{}
		t1 := []any{}
		t1 = append(t1, str_concat)
		t1 = append(t1, p.M_Player.M_DwUin)
		params = append(params, t1)

		sqlStr := "SELECT * FROM t_player_Friend_Data WHERE dwUin = ?"
		sqlStruck := db.SqlFriendStruct{}
		sqlStruck.FriendList = ""
		if err := db.SqlDb.Get(&sqlStruck, sqlStr, req.PlayerId); err != nil {

		} else {

		}
		if sqlStruck.FriendList != "" {
			arr := strings.Split(sqlStruck.FriendList, "_")
			for i := 0; i < len(arr); i++ {
				id, _ := strconv.ParseInt(arr[i], 10, 32)
				if id == int64(p.M_Player.M_DwUin) {
					arr = append(arr[:i], arr[i+1:]...)
					break
				}
			}
			sqlStrs = append(sqlStrs, "UPDATE t_player_Friend_Data SET FriendList = ? WHERE dwUin = ?")
			str_concat := strings.Join(arr, "_")
			t2 := []any{}
			t2 = append(t2, str_concat)
			t2 = append(t2, req.PlayerId)
			params = append(params, t2)
		}
		err := db.SeriesTransaction(sqlStrs, params)
		if err == nil {
			player, ok := G_GameLogicPtr.M_Players[req.PlayerId]
			if ok {
				if player.GetGameData("PlayerFriendData") != nil {
					player.GetIFGameData("PlayerFriendData").(*PlayerFriendData).NotifySuccessDeleteFriend(p.M_Player.M_DwUin)
				}
			}
		}
		EventAuid, sqlst, friendInfo := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).NewFriendEventToDb(14, p.M_Player.M_DwUin, req.PlayerId, []interface{}{})
		p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).NotifyNewFriendEvent(EventAuid, sqlst, friendInfo)

	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResDeleteFriend", data)
}

func (p *PlayerFriendData) NotifySuccessDeleteFriend(FriendId int32) {
	notify := &msg.NotifyDeleteFriend{}
	notify.PlayerId = FriendId

	for i := 0; i < len(p.Data.FriendInfos); i++ {
		if p.Data.FriendInfos[i].DwUin == FriendId {
			p.Data.FriendInfos = append(p.Data.FriendInfos[:i], p.Data.FriendInfos[i+1:]...)
			break
		}
	}
	proto.Marshal(notify)
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyDeleteFriend", data)
}

// ///////////////////
type PlayerFriendEventData struct {
	*PlayerData
	Data       msg.ResFriendEventData
	MsqlStruck []db.SqlFriendEventStruct
}

func (p *PlayerFriendEventData) LoadDataFromDB(dwUin interface{}) bool {

	sqlStr := "SELECT * FROM t_Friend_Event_Data WHERE dwUin = ?"
	p.MsqlStruck = []db.SqlFriendEventStruct{}
	p.Data.MFriendEventData = []*msg.FriendEventData{}

	if err := db.SqlDb.Select(&p.MsqlStruck, sqlStr, dwUin.(int32)); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		p.IsHaveDataDb = false
	} else {
		p.IsHaveDataDb = true
	}
	sort.Slice(p.MsqlStruck, func(i, j int) bool { return p.MsqlStruck[i].EventStartTime > p.MsqlStruck[j].EventStartTime })

	p.DeleteOutRangeEvent(30)
	for i := 0; i < len(p.MsqlStruck); i++ {
		item := msg.FriendEventData{}
		item.AutoId = p.MsqlStruck[i].AutoId
		item.EventStartTime = p.MsqlStruck[i].EventStartTime
		item.EventType = p.MsqlStruck[i].EventType
		item.EventParam = p.MsqlStruck[i].EventParam
		item.MFriendInfo = p.GetFriendInfoByEvent(p.MsqlStruck[i].EventType, p.MsqlStruck[i].EventParam)
		p.Data.MFriendEventData = append(p.Data.MFriendEventData, &item)
	}

	p.Reconnect(false)
	return true
}

func (p *PlayerFriendEventData) DeleteOutTimelineEvent(deleteList []int32, tableName string) {
	sqlStr := "DELETE FROM " + tableName + " WHERE auto_id = ?"
	for i := 0; i < len(deleteList); i++ {

		result, err := db.SqlDb.Exec(sqlStr, deleteList[i])
		if err != nil {
			fmt.Printf("exec failed, err:%v\n", err)
			return
		}
		affectedRows, err := result.RowsAffected()
		if err != nil {
			fmt.Printf("get affected failed, err:%v\n", err)
			return
		}
		fmt.Printf("delete data success, affected rows:%d\n", affectedRows)
	}
}

func (p *PlayerFriendEventData) DeleteOutRangeEvent(eventCnt int) {
	cnt := 0
	deleteIDs := []int32{}
	SqlList := []db.SqlFriendEventStruct{}
	for i := 0; i < len(p.MsqlStruck); i++ {
		if p.MsqlStruck[i].EventType != 1 && p.MsqlStruck[i].EventType != 6 && p.MsqlStruck[i].EventType != 7 && p.MsqlStruck[i].EventType != 8 && p.MsqlStruck[i].EventType != 11 {
			cnt = cnt + 1
			if cnt > eventCnt {
				deleteIDs = append(deleteIDs, p.MsqlStruck[i].AutoId)
			} else {
				SqlList = append(SqlList, p.MsqlStruck[i])
			}
		} else {
			SqlList = append(SqlList, p.MsqlStruck[i])
		}
	}
	p.MsqlStruck = SqlList
	p.DeleteOutTimelineEvent(deleteIDs, "t_Friend_Event_Data")

}

func (p *PlayerFriendEventData) GetFriendInfoByEvent(Eventtype int32, eventParam string) *msg.FriendInfo {
	strr := strings.Split(eventParam, "_")
	id, _ := strconv.Atoi(strr[0])
	friendDwuin := int32(id)
	Profile := G_GameLogicPtr.MPlayerProfileManager.GetPlayerProfile(friendDwuin)
	friendInfo := &msg.FriendInfo{}

	if Profile != nil {
		friendInfo.ImageFrame = Profile.ImageFrame
		friendInfo.ImageIcon = Profile.ImageIcon
		friendInfo.NickName = Profile.NickName
		friendInfo.DwUin = Profile.DwUin
		friendInfo.DecorateCnt = 0
	} else {
		friendInfo.ImageFrame = 1
		friendInfo.ImageIcon = 1
		friendInfo.NickName = "Player" + strconv.Itoa(int(friendDwuin))
		friendInfo.DwUin = friendDwuin
		friendInfo.DecorateCnt = 0

		sql := &db.SqlPlayerProfileStruct{}
		sql.DwUin = friendDwuin
		sql.ImageFrame = 1
		sql.ImageIcon = 1
		sql.NickName = "Player" + strconv.Itoa(int(friendDwuin))
		sql.PicURL = ""
		G_GameLogicPtr.MPlayerProfileManager.UpdateNewProfile(sql)
	}
	return friendInfo
}

func (p *PlayerFriendEventData) InitEventParamAndFriendInfo(Eventtype int32, friendDwuin int32, args []interface{}) (*msg.FriendInfo, string) {
	Profile := G_GameLogicPtr.MPlayerProfileManager.GetPlayerProfile(friendDwuin)
	friendInfo := &msg.FriendInfo{}
	EventParam := ""
	if Profile != nil {
		friendInfo.ImageFrame = Profile.ImageFrame
		friendInfo.ImageIcon = Profile.ImageIcon
		friendInfo.NickName = Profile.NickName
		friendInfo.DwUin = Profile.DwUin
		friendInfo.DecorateCnt = 0
	} else {
		friendInfo.ImageFrame = 1
		friendInfo.ImageIcon = 1
		friendInfo.NickName = "Player" + strconv.Itoa(int(friendDwuin))
		friendInfo.DwUin = friendDwuin
		friendInfo.DecorateCnt = 0

		sql := &db.SqlPlayerProfileStruct{}
		sql.DwUin = friendDwuin
		sql.ImageFrame = 1
		sql.ImageIcon = 1
		sql.NickName = "Player" + strconv.Itoa(int(friendDwuin))
		sql.PicURL = ""
		G_GameLogicPtr.MPlayerProfileManager.UpdateNewProfile(sql)
	}
	if Eventtype == 1 {
		EventParam = strconv.Itoa(int(friendDwuin)) + "_" + strconv.Itoa(int(args[0].(int32))) //好友id+申请AutoId
	}
	if Eventtype == 2 {
		EventParam = strconv.Itoa(int(friendDwuin)) + "_" + strconv.Itoa(int(args[0].(int32))) //好友id+申请AutoId
	}
	if Eventtype == 3 {
		EventParam = strconv.Itoa(int(friendDwuin)) + "_" + strconv.Itoa(int(args[0].(int32))) + "_" + strconv.Itoa(int(args[1].(int32))) //好友id+申请AutoId+卡牌ID
	}
	if Eventtype == 4 {
		EventParam = strconv.Itoa(int(friendDwuin)) + "_" + strconv.Itoa(int(args[0].(int32))) + "_" + strconv.Itoa(int(args[1].(int32))) //好友id+申请AutoId+卡牌ID
	}
	if Eventtype == 5 {
		EventParam = strconv.Itoa(int(friendDwuin)) + "_" + strconv.Itoa(int(args[0].(int32))) + "_" + strconv.Itoa(int(args[1].(int32))) //好友id+申请AutoId+卡牌ID
	}
	if Eventtype == 6 {
		EventParam = strconv.Itoa(int(friendDwuin)) + "_" + strconv.Itoa(int(args[0].(int32))) + "_" + strconv.Itoa(int(args[1].(int32))) + "_" + strconv.Itoa(int(args[2].(int32))) //好友id+申请AutoId+卡牌ID+卡牌ID
	}
	if Eventtype == 7 {
		EventParam = strconv.Itoa(int(friendDwuin)) + "_" + strconv.Itoa(int(args[0].(int32))) + "_" + strconv.Itoa(int(args[1].(int32))) //好友id+申请AutoId+卡牌ID
	}
	if Eventtype == 8 {
		EventParam = strconv.Itoa(int(friendDwuin)) + "_" + strconv.Itoa(int(args[0].(int32))) + "_" + strconv.Itoa(int(args[1].(int32))) //好友id+申请AutoId+卡牌ID
	}

	if Eventtype == 9 {
		EventParam = strconv.Itoa(int(friendDwuin)) + "_" + strconv.Itoa(int(args[0].(int32))) + "_" + strconv.Itoa(int(args[1].(int32))) + "_" + strconv.Itoa(int(args[2].(int32))) //好友id+申请AutoId+卡牌ID+卡牌ID
	}
	if Eventtype == 10 {
		EventParam = strconv.Itoa(int(friendDwuin)) + "_" + strconv.Itoa(int(args[0].(int32))) + "_" + strconv.Itoa(int(args[1].(int32))) + "_" + strconv.Itoa(int(args[2].(int32))) //好友id+申请AutoId+卡牌ID+卡牌ID
	}

	if Eventtype == 11 {
		EventParam = strconv.Itoa(int(friendDwuin)) + "_" + strconv.Itoa(int(args[0].(int32))) + "_" + strconv.Itoa(int(args[1].(int32))) + "_" + strconv.Itoa(int(args[2].(int32))) //好友id+申请AutoId+卡牌ID+卡牌ID
	}
	if Eventtype == 12 {
		EventParam = strconv.Itoa(int(friendDwuin)) + "_" + args[0].(string) + "_" + strconv.Itoa(int(args[1].(int32)))
	}
	if Eventtype == 14 {
		EventParam = strconv.Itoa(int(friendDwuin))
	}
	return friendInfo, EventParam
}

func (p *PlayerFriendEventData) Reconnect(b bool) {
	if b {
		p.LoadDataFromDB(p.M_Player.M_DwUin)
	}
}

func (p *PlayerFriendEventData) ClearData() bool {
	p.SaveDataFromDB("")

	return true
}
func (p *PlayerFriendEventData) SaveDataToDB(AutoId int32) {
	for i := 0; i < len(p.MsqlStruck); i++ {
		if p.MsqlStruck[i].AutoId == AutoId {
			db.FormatAllMemUpdateDb(&p.MsqlStruck[i], "t_Friend_Event_Data", "auto_id")
		}
	}
}

func (p *PlayerFriendEventData) NewFriendEventToDb(Eventtype int32, TargetDwuin int32, friendDwuin int32, args []interface{}) (int32, *db.SqlFriendEventStruct, *msg.FriendInfo) {
	sqlStruck := db.SqlFriendEventStruct{}
	sqlStruck.DwUin = TargetDwuin
	sqlStruck.EventStartTime = int32(time.Now().Unix())
	sqlStruck.EventType = Eventtype
	friendInfo, EventParam := p.InitEventParamAndFriendInfo(Eventtype, friendDwuin, args)
	sqlStruck.EventParam = EventParam

	SqlList := []db.SqlFriendEventStruct{sqlStruck}
	p.MsqlStruck = append(SqlList, p.MsqlStruck...)

	insertId, _ := db.FormatAllMemInsertDb(&sqlStruck, "t_Friend_Event_Data")
	return int32(insertId), &sqlStruck, friendInfo
}

func (p *PlayerFriendEventData) NotifyNewFriendEvent(insertId int32, sqlStruck *db.SqlFriendEventStruct, friendInfo *msg.FriendInfo) {

	notify := &msg.NotifyNewFriendEvent{}
	event := &msg.FriendEventData{}
	event.EventStartTime = sqlStruck.EventStartTime
	event.EventType = sqlStruck.EventType
	event.EventParam = sqlStruck.EventParam
	event.MFriendInfo = friendInfo
	event.AutoId = insertId

	notify.DwUin = p.M_Player.M_DwUin
	notify.NewEvent = event
	list := []*msg.FriendEventData{event}
	p.Data.MFriendEventData = append(list, p.Data.MFriendEventData...)

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyNewFriendEvent", data)
}

func (p *PlayerFriendEventData) DeleteEventDbData(dwUin int32, Eventtype int32, AutoId int32) int32 {
	sqlStr := "SELECT * FROM t_Friend_Event_Data WHERE dwUin = ? AND EventType = ?"
	MsqlStruck := []db.SqlFriendEventStruct{}
	if err := db.SqlDb.Select(&MsqlStruck, sqlStr, dwUin, Eventtype); err != nil {

	} else {

	}
	if Eventtype == 1 || Eventtype == 6 || Eventtype == 7 || Eventtype == 8 || Eventtype == 11 {
		for i := 0; i < len(MsqlStruck); i++ {
			units := strings.Split(MsqlStruck[i].EventParam, "_")
			v, _ := strconv.Atoi(units[1])
			if AutoId == int32(v) {
				sqlStr := "DELETE FROM " + "t_Friend_Event_Data" + " WHERE auto_id = ?"
				db.SqlDb.Exec(sqlStr, MsqlStruck[i].AutoId)
				return MsqlStruck[i].AutoId
			}
		}
	}
	return 0
}

func (p *PlayerFriendEventData) DeleteLocalDataByAutoId(AutoId int32) {
	for i := 0; i < len(p.MsqlStruck); i++ {
		if p.MsqlStruck[i].AutoId == AutoId {
			p.MsqlStruck = append(p.MsqlStruck[:i], p.MsqlStruck[i+1:]...)
			break
		}
	}
	for i := 0; i < len(p.Data.MFriendEventData); i++ {
		if p.Data.MFriendEventData[i].AutoId == AutoId {
			p.Data.MFriendEventData = append(p.Data.MFriendEventData[:i], p.Data.MFriendEventData[i+1:]...)
			break
		}
	}

	notify := &msg.NotifyFriendEventComplete{}
	notify.AutoId = AutoId
	notify.DwUin = p.M_Player.M_DwUin

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyFriendEventComplete", data)
}

func (p *PlayerFriendEventData) SaveDataFromDB(Key interface{}) bool {

	return true
}

func (p *PlayerFriendEventData) ReqFriendEventData(buf []byte) {
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(&p.Data)
	G_getGameLogic().PackResInfo(agent, "ResFriendEventData", data)
	p.SaveDataFromDB("")
}
